package cn.dark.auth.core.tokengenerate;

import cn.dark.auth.core.KeyGenerateUtil;
import cn.dark.auth.core.repository.LoginRepository;
import cn.dark.auth.core.SysConfig;
import cn.dark.auth.core.exception.AuthBaseException;
import cn.hutool.extra.spring.SpringUtil;

/**
 * @author dark
 * @date 2023-10-27
 */
public abstract class AbstractTokenGenerator implements TokenGenerator {

    @Override
    public String generateToken(Object loginId, String device) {
        int retryTime = 0;
        String token = doGenerate(loginId, device);
        LoginRepository loginRepository = SpringUtil.getBean(LoginRepository.class);

        while (loginRepository.hasKey(KeyGenerateUtil.getKeyByToken(token))) {
            // -1表示一直重试直到生成成功
            if (SysConfig.getTokenGenRetryMaxTime() != -1
                && ++retryTime > SysConfig.getTokenGenRetryMaxTime()) {
                throw new AuthBaseException("生成Token失败，Token重复");
            }

            token = doGenerate(loginId, device);
        }

        return token;
    }

    protected abstract String doGenerate(Object loginId, String device);
}
